const express = require('express')
const app = express()
const bodyParser = require('body-parser')

// 处理静态资源
app.use(express.static('public'))
    // 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 设置允许跨域成功访问该服务
// 设置允许跨域返回问该服务
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Origin", 'PUT,GET,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Origin", 'X-Requested-With');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
})

app.get('/fdata', (req, res) => {
    res.send('Hello fecth')
})
app.get('/books', (req, res) => {
    res.send('传统的URL传递参数' + req.query.id)
})
app.delete('/books/:id', (req, res) => {
    res.send('delete请求传递参数' + req.params.id)
})
app.post('/books', (req, res) => {
    res.send('post请求传递参数' + req.body.uname + '----' + req.body.pwd)
})
app.put('/books/:id', (req, res) => {
    res.send('put请求传递参数' + req.params.id + '---' + req.body.uname + '----' + req.body.pwd)
})

app.get('/json', (req, res) => {
    res.json({
        uname: 'list',
        age: 13,
        gender: 'male'
    })
})

app.get('/a1', (req, res) => {
    setTimeout(function() {
        res.send('hello Tom')
    }, 1000)
})
app.get('/a2', (req, res) => {
    setTimeout(function() {
        res.send('hello world')
    }, 2000)
})
app.get('/a3', (req, res) => {
    setTimeout(function() {
        res.send('hello Jerry')
    }, 3000)
})

// 路由
app.get('/data', (req, res) => {
    res.send('Hello world')
});
app.get('/data1', (req, res) => {
    res.send('Hello Tom')
});
app.get('/data2', (req, res) => {
    res.send('Hello Jerry')
});


// 启动路由监听
app.listen(3000, () => {
    console.log('running ');
})